package com.zjkj.mp.controller.messageManage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zjkj.mp.service.channel.ChannelService;
import com.zjkj.mp.service.customer.CustomerManagerService;
import com.zjkj.mp.service.message.MessageService;
import com.zjkj.mp.service.user.UserService;
import com.zjkj.mp.utils.Toolkit;
import com.zjkj.mp.utils.security.SpringSecurityUtils;
import com.zjkj.mp.vo.channel.MpChannel;
import com.zjkj.mp.vo.customer.ContactPerson;
import com.zjkj.mp.vo.message.Message;
import com.zjkj.mp.vo.message.MessageState;
import com.zjkj.mp.vo.user.MpUser;
import com.zjkj.mp.vo.user.USER_ZT;

/**
 * 
 * 发送短信控制器
 *
 * @author 陈晨
 * @history
 * <TABLE id="HistoryTable" border="1">
 * 	<TR><TD>时间</TD><TD>描述</TD><TD>作者</TD></TR>
 *	<TR><TD>2013-6-9</TD><TD>创建初始版本</TD><TD>陈晨</TD></TR>
 * </TABLE>
 */
@Controller
public class SendMessageController {

	@Resource
	private Toolkit tool;
	@Resource(name = "customerManagerServiceImpl")
	private CustomerManagerService customerService;
	@Resource(name = "channelServiceImpl")
	private ChannelService channelService;
	@Resource(name="messageServiceImpl")
	private MessageService messageService;
	@Resource(name = "userServiceImpl")
	private UserService userService;

	/******************************* 发送短信 ***********************************/
	
	/**
	 * 导入号码数据信息（txt类型）
	 * @return
	 */
	@RequestMapping("/importData.do")
	public String showAllListById(HttpServletRequest req, 
			@RequestParam(value="importData",required=false) MultipartFile importData) {
		String fileName = importData.getOriginalFilename();
		String content;
		if(fileName==null||"".equals(fileName)){
			req.setAttribute("MSG", "导入的文件不能为空，请重新导入");
			return "message/sendMessage";
		}
		String typeName = fileName.split("\\.")[1];
		if(!("txt".equals(typeName))){
			req.setAttribute("MSG", "导入的文件格式不正确，请重新导入");
			return "message/sendMessage";
		}else{
			StringBuffer strBuffer = new StringBuffer(); 
			try {
				InputStream input = importData.getInputStream();
				InputStreamReader inputReader = new InputStreamReader(input, "UTF-8");            
				BufferedReader bufferReader = new BufferedReader(inputReader);                         
				// 读取一行   
				String line = null;    
				while ((line = bufferReader.readLine()) != null){     
					strBuffer.append(line);  
				} 
			} catch (IOException e) {
				e.printStackTrace();
			}
			req.setAttribute("MSG", "导入成功");
			String str = strBuffer.toString();
			content = tool.AnalyseInfo(str);
		}
		//获取开启通道列表信息
		List<MpChannel> list = channelService.getMpChannelListStart(1);
		req.setAttribute("list", list);
		//获取用户短信剩余数
		int userId = ((MpUser)(SpringSecurityUtils.getCurrentUser())).getUserId();
		long messageCount = userService.findUserById(userId).getBalance();
		req.setAttribute("messageCount", messageCount);
		req.setAttribute("content", content);
		return "message/sendMessage";
	}
	
	@RequestMapping("/delSameNumber.do")
	public String delSameNumber(HttpServletRequest req){
		String phoneContent = req.getParameter("phoneContent");
		phoneContent = tool.delSameNumber(phoneContent); 
		//获取开启通道列表信息
		List<MpChannel> list = channelService.getMpChannelListStart(1);
		req.setAttribute("list", list);
		//获取用户短信剩余数
		int userId = ((MpUser)(SpringSecurityUtils.getCurrentUser())).getUserId();
		long messageCount = userService.findUserById(userId).getBalance();
		req.setAttribute("messageCount", messageCount);
		req.setAttribute("phoneContent", phoneContent);
		return "message/sendMessage";
	}
	
	@RequestMapping("/analyseNumber.do")
	public String analyseNumber(HttpServletRequest req){
		String phoneContent = req.getParameter("phoneContent");
		//获取号码分组信息
		Map<String, Object> map = new HashMap<String, Object>();
		map = tool.messageList(phoneContent);
		req.setAttribute("map", map);
		//获取开启通道列表信息
		List<MpChannel> list = channelService.getMpChannelListStart(1);
		req.setAttribute("list", list);
		//获取用户短信剩余数
		int userId = ((MpUser)(SpringSecurityUtils.getCurrentUser())).getUserId();
		long messageCount = userService.findUserById(userId).getBalance();
		req.setAttribute("messageCount", messageCount);
		//把去重后的号码总合，存储在隐藏文件区域中，发送时候调用
		req.setAttribute("t_phoneContent", phoneContent);
		return "message/sendMessage";
	}
	
	@ResponseBody
	@RequestMapping("/sendMessageInfo.do")
	public String sendMessageInfo(HttpServletRequest req, HttpServletResponse res){
		
		//1、判断用户是否在黑名单
		String userState = ((MpUser)(SpringSecurityUtils.getCurrentUser())).getUserState();
		if(USER_ZT.JYZ==userState||USER_ZT.JYZ.equals(userState)){
			//用户状态是黑名单
			return MessageState.getStateName("HMD_OK");
		}
		
		String channel = ServletRequestUtils.getStringParameter(req, "channel", null);
		if(null==channel||"null".equals(channel)){
			return MessageState.getStateName("TD_NO");
		}
		String numbers = ServletRequestUtils.getStringParameter(req, "t_phoneContent", null);
		if(numbers.length()==0){
			return MessageState.getStateName("QCFX_NO");
		}
		String sendInfo = ServletRequestUtils.getStringParameter(req, "sendInfo", null);
		System.out.println("通道ID："+channel+" 号码组："+numbers+" 发送信息："+sendInfo);
		
		//2、判断用户短信余额数目
		long balance = ((MpUser)(SpringSecurityUtils.getCurrentUser())).getBalance();
		if(balance<=0||balance<numbers.split(",").length){
			return MessageState.getStateName("BAL_NO");
		}
		
		//3、判断用户信息是否需要审核
		boolean audit = ((MpUser)(SpringSecurityUtils.getCurrentUser())).isAudit();
		//4、存入短信发送信息到fs_jl中
		Message message = new Message();
		message = messageService.saveMessage(sendInfo);
		//短信发送完毕后的返回信息
		String msg = null;
		if(audit){
			//需要审核，审核中
			messageService.updateMessageState(message.getFsId(), "00");
			return MessageState.getStateName("NEW");
		}else{
			//不需要审核则进行
			//5、短信的发送方式：定时短信或者是及时短信
			String day = ServletRequestUtils.getStringParameter(req, "day", null);
			String hour = ServletRequestUtils.getStringParameter(req, "hour", null);
			
			if((null==day||"".equals(day))&&(null==hour||"".equals(hour))){
				//6、一般短信发送一条记录，明细表添加一条信息
				msg = messageService.sendMessage(channel, numbers, sendInfo, message, balance); //发送短信通道、号码群、发送信息
			}else{
				//定时短信发送
			}
		}
		//7、记录到日志记录表中
		messageService.saveLogger(msg);
		return msg;
	}
	
	@ResponseBody
	@RequestMapping("/importPhones.do")
	public String importPhones(HttpServletRequest req, HttpServletResponse res) throws Exception{
		String group = req.getParameter("group");
		int groupId = Integer.parseInt(group);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("groupId", groupId);
		List<ContactPerson> list = customerService.getContactPersonList(map);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			String number = (String)list.get(i).getMovePhoneNumber();
			sb.append(number).append(",");
		}
		String numbers = sb.toString();
		if(numbers.length()==0){
			//...
		}else{
			numbers = numbers.substring(0, numbers.length()-1);
		}
		return numbers;
	}

}
